import axios from 'axios'
import { Toast } from 'vant'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: 'https://api.opendota.com', // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.status !== 200) {
      Toast.fail(response.msg || 'Error')
      return Promise.reject(new Error(response.msg || 'Error'))
    } else {
      return response.data
    }
  },
  error => {
    console.log(error) // for debug
    const message = error.msg || '服务器忙碌，请稍后再试'
    Toast.fail(message)
    router.push({
      name:'500'
    })
    return Promise.reject(error)
  }
)

export default service